package com.ruoyi.kiku.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.tt.WeiboSupetopicSigner;
import com.ruoyi.kiku.domain.KikuStationSisterBasic;
import com.ruoyi.kiku.mapper.KikuStationSisterBasicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.kiku.mapper.KikuStationSisterDetailsMapper;
import com.ruoyi.kiku.domain.KikuStationSisterDetails;
import com.ruoyi.kiku.service.IKikuStationSisterDetailsService;

/**
 * 小鞠站姐详细信息Service业务层处理
 *
 * @author TT
 * @date 2025-08-24
 */
@Service
public class KikuStationSisterDetailsServiceImpl implements IKikuStationSisterDetailsService
{
    @Autowired
    private KikuStationSisterDetailsMapper kikuStationSisterDetailsMapper;
    @Autowired
    private KikuStationSisterBasicMapper kikuStationSisterBasicMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询小鞠站姐详细信息
     *
     * @param id 小鞠站姐详细信息主键
     * @return 小鞠站姐详细信息
     */
    @Override
    public KikuStationSisterDetails selectKikuStationSisterDetailsById(Long id)
    {
        return kikuStationSisterDetailsMapper.selectKikuStationSisterDetailsById(id);
    }

    /**
     * 查询小鞠站姐详细信息列表
     *
     * @param kikuStationSisterDetails 小鞠站姐详细信息
     * @return 小鞠站姐详细信息
     */
    @Override
    public List<KikuStationSisterDetails> selectKikuStationSisterDetailsList(KikuStationSisterDetails kikuStationSisterDetails)
    {
        return kikuStationSisterDetailsMapper.selectKikuStationSisterDetailsList(kikuStationSisterDetails);
    }

    /**
     * 新增小鞠站姐详细信息
     *
     * @param kikuStationSisterDetails 小鞠站姐详细信息
     * @return 结果
     */
    @Override
    public int insertKikuStationSisterDetails(KikuStationSisterDetails kikuStationSisterDetails)
    {
        kikuStationSisterDetails.setCreateTime(DateUtils.getNowDate());
        return kikuStationSisterDetailsMapper.insertKikuStationSisterDetails(kikuStationSisterDetails);
    }

    /**
     * 修改小鞠站姐详细信息
     *
     * @param kikuStationSisterDetails 小鞠站姐详细信息
     * @return 结果
     */
    @Override
    public int updateKikuStationSisterDetails(KikuStationSisterDetails kikuStationSisterDetails)
    {
        kikuStationSisterDetails.setUpdateTime(DateUtils.getNowDate());
        return kikuStationSisterDetailsMapper.updateKikuStationSisterDetails(kikuStationSisterDetails);
    }

    /**
     * 批量删除小鞠站姐详细信息
     *
     * @param ids 需要删除的小鞠站姐详细信息主键
     * @return 结果
     */
    @Override
    public int deleteKikuStationSisterDetailsByIds(Long[] ids)
    {
        return kikuStationSisterDetailsMapper.deleteKikuStationSisterDetailsByIds(ids);
    }

    /**
     * 删除小鞠站姐详细信息信息
     *
     * @param id 小鞠站姐详细信息主键
     * @return 结果
     */
    @Override
    public int deleteKikuStationSisterDetailsById(Long id)
    {
        return kikuStationSisterDetailsMapper.deleteKikuStationSisterDetailsById(id);
    }

    /**
     *  同步全部的站姐信息
     * @return int
     */
    @Override
    public int allSynchronousKikuStationSisterDetails() throws Exception {
        KikuStationSisterBasic query = new KikuStationSisterBasic();
        query.setIsCancelled(0);
        List<KikuStationSisterBasic> list
                = kikuStationSisterBasicMapper.selectKikuStationSisterBasicList(query);
        Long userId = SecurityUtils.getUserId();
        String cookie = redisCache.getCacheObject("0_cookie:" + userId);
        WeiboSupetopicSigner signer= new WeiboSupetopicSigner(cookie);
        List<KikuStationSisterDetails> kikuStationSisterDetails = new ArrayList<KikuStationSisterDetails>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject userInfo = signer.getUserInfoByUid(list.get(i).getWeiboUserId());
            KikuStationSisterDetails details = new KikuStationSisterDetails();

            // 设置基本信息
            Long weiboUserId = userInfo.getLong("id");
            details.setWeiboUserId(weiboUserId);
            details.setNickname(userInfo.getString("screen_name"));

            // 设置性别（根据JSON中的"gender"字段，"f"表示女，"m"表示男）
            String gender = userInfo.getString("gender");
            if ("f".equals(gender)) {
                details.setGender(2); // 2表示女
            } else if ("m".equals(gender)) {
                details.setGender(1); // 1表示男
            } else {
                details.setGender(0); // 0表示未知
            }

            // 设置粉丝数、关注数和微博数
            details.setFansCount(userInfo.getLong("followers_count"));
            details.setFollowCount(userInfo.getLong("friends_count"));
            details.setWeiboCount(userInfo.getLong("statuses_count"));

            // 设置转评赞总数
            JSONObject statusTotalCounter = userInfo.getJSONObject("status_total_counter");
            long repostCount = parseFormattedNumber(statusTotalCounter.getString("repost_cnt"));
            long commentCount = parseFormattedNumber(statusTotalCounter.getString("comment_cnt"));
            long likeCount = parseFormattedNumber(statusTotalCounter.getString("like_cnt"));
            long totalCnt = parseFormattedNumber(statusTotalCounter.getString("total_cnt"));
            details.setRepostCommentLike(totalCnt);

            // 设置单独的评论量、点赞量和转发量
            details.setCommentCount(commentCount);
            details.setLikeCount(likeCount);
            details.setRepostCount(repostCount);

            // 设置介绍
            details.setDescription(userInfo.getString("description"));
            KikuStationSisterDetails flagObject= kikuStationSisterDetailsMapper.selectKikuStationSisterDetailsByWeiboUserId(weiboUserId);
            if (flagObject == null) {
                kikuStationSisterDetailsMapper.insertKikuStationSisterDetails(details);
            }else {
                kikuStationSisterDetails.add(details);
            }

       }
       if (!kikuStationSisterDetails.isEmpty()) {
          return kikuStationSisterDetailsMapper.batchUpdateKikuStationSisterDetails(kikuStationSisterDetails);
       }else {
           return -1;
       }
    }
    // 辅助方法：将格式化数字字符串（如"611,132"）转换为long类型
    private long parseFormattedNumber(String formattedNumber) {
        if (formattedNumber == null || formattedNumber.isEmpty()) {
            return 0L;
        }
        // 移除数字中的逗号
        String cleanNumber = formattedNumber.replace(",", "");
        try {
            return Long.parseLong(cleanNumber);
        } catch (NumberFormatException e) {
            return 0L;
        }
    }
}
